<?php

namespace app\api\model\cps;

use app\api\model\ExtendConsume;
use app\api\model\UserConsumeLog;
use app\common\model\User;
use app\shopapi\model\ExtendConsumeShop;
use think\Request;

class Didi
{

    public $url = "https://union.didi.cn/openapi/v1.0/link/generate";

    public $orderurl = "https://union.didi.cn/openapi/v1.0/order/list";

    public $ceshiorderurl = "https://union.didi.cn/openapi/v1.0/orderMock/callback";

    public $AppKey       = "bdpYbM3mB0ObdF94";

    public $accesskey    = "vSm6ffsQuTyxm8pRyM26wzejdTTnfh1V";

    public $promotion_id = "7229731839886914673";


    public function getProductList()
    {
        $data = ['159'=>'滴滴加油','210'=>' 滴滴网约车','393'=>'滴滴货运','500'=>'花小猪','120'=>'滴滴代驾','842'=>'滴滴洗车','40068'=>'滴滴租车'];

        return $data;
    }

    public function activity($activity_id,$user_id)
    {
        $Timestamp = time();

        $param_to_sign = array(
            "App-Key"      =>    $this->AppKey,
            "Timestamp"    =>    $Timestamp,
            "source_id"    =>    $user_id,
            "activity_id"  =>    $activity_id,
            "link_type"    =>    "mini",
            "promotion_id" =>    $this->promotion_id
        );

        $sign = $this->get_sign($param_to_sign, $this->accesskey);
        //由于promotion在json里必须为数字类型，这里用字符串格式化的方式避免被科学计数法。我不是专业的php程序员，如有合理的方法，欢迎向我们提供
        $json = sprintf("{\"activity_id\":%d,\"source_id\":\"%s\",\"link_type\":\"%s\",\"promotion_id\":%s}", $activity_id, $user_id, "mini", $this->promotion_id);

        $header = array(
            "App-Key: ".$this->AppKey,
            "Timestamp: ". $Timestamp,
            "Sign: ".$sign,
            "Content-Type: application/json",
            "Content-Length: ".strlen($json)
        );

        //请求生成短链
        $link_response = json_decode($this->post($this->url, $json, $header), true);
        if ($link_response['errno']==0){
            return $link_response['data'];
        } else {
            throw new \Exception($link_response['errmsg']);
        }

    }

    //查询未结算的订单
    /*public function unliquidated()
    {
        $lists = UserConsumeLog::where(['cps_type'=>5,'consume_type'=>2,'is_to_account'=>0])->field('pay_time')->select();

        foreach ($lists as $k=>$v){
            $start = $v['pay_time']-3600;
            $end = $v['pay_time'];
            $res = $this->order(1,$start,$end);
        }
    }*/


    public function order($type=0,$start='',$end='')
    {
        $Timestamp = time();

        $pay_start_time = strtotime("today");
        //$pay_start_time = 1729153802;
        //$pay_end_time = 1729155602;

        $pay_end_time = strtotime("tomorrow") - 1;
        if ($type==1){
            $pay_start_time = $start;
            $pay_end_time = $end;
        }
        $param_to_sign = array(
            "App-Key"      =>    $this->AppKey,
            "Timestamp"    =>    $Timestamp,
            "pay_start_time" =>  $pay_start_time,
            'pay_end_time'  =>  $pay_end_time
        );

        $param = array(
            "pay_start_time"    => $pay_start_time,
            'pay_end_time'      =>  $pay_end_time
        );

        $request = Request::instance();
        $domain=$request->domain();

        $sign = $this->get_sign($param_to_sign, $this->accesskey);
        $header = array(
            "App-Key: ".$this->AppKey,
            "Timestamp: ". $Timestamp,
            "Sign: ".$sign
        );
        $ProductList = $this->getProductList();

        //请求生成短链
        $link_response = json_decode($this->get($this->orderurl, $param, $header), true);
        if ($link_response['errno']==0){
            $order_list = $link_response['data']['order_list'];

            foreach ($order_list as $k=>$v){

                $promotion_amount = $v['cps_profit']>0?$v['cps_profit']:$v['cpa_profit'];

                $total_commission = $promotion_amount/100;

                $commission = $total_commission*0.56;
                $user = User::get($v['source_id']);
                if ($user){
                    //增加消费记录
                    $consume_log_info = UserConsumeLog::get([ 'user_id'=>$v['source_id'], 'order_no'=>$v['order_id']]);
                    if (!$consume_log_info){
                        $consume_log_model = new UserConsumeLog();

                        $consume_log_data = [
                            'user_id'=>$v['source_id'],
                            'title'=>$v['title'].$ProductList[$v['product_id']],
                            'shop_id'=>0,
                            'shop_name'=>'滴滴',
                            'image'=>$domain.'/assets/img/didi.png',
                            'order_no'=>$v['order_id'],
                            'pay_time'=>$v['pay_time'],
                            'pay_price'=>$v['pay_price']/100,
                            'consume_type'=>2,
                            'cps_type'=>5,
                            'goods_id'=>$v['product_id'],
                            'commission'=>$commission,
                            'total_commission'=>$total_commission,
                            'order_status_name'=>'已付款'
                        ];

                        $consume_log_model->save($consume_log_data);
                        UserConsumeLog::lockMemberConsumeCalculate($v['source_id'],$consume_log_model->total_commission,$consume_log_model->consume_id,0);
                        UserConsumeLog::newrecommendShopConsumeCalculate($v['source_id'],0,$consume_log_model->total_commission,$consume_log_model->consume_id,2);
                    } else {
                        if ($v['fail_reason']=='success'&&$consume_log_info->is_to_account==0){
                            /*if ($v['status']==7){
                                //发放消费记录的收益
                                UserConsumeLog::sendCommission($consume_log_info->order_no);
                            }*/
                        } elseif ($v['fail_reason']=='refund'&&$consume_log_info->is_refund==0){
                            $consume_log_info->commission = 0;
                            $consume_log_info->order_status_name = '退款成功';
                            $consume_log_info->is_refund = 1;
                            $consume_log_info->save();
                            ExtendConsume::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                            ExtendConsumeShop::update(['commission'=>0],['consume_log_id'=>$consume_log_info->consume_id]);
                        }
                    }
                }

            }

            return $order_list;
        } else {
            throw new \Exception($link_response['errmsg']);
        }
    }

    public function ceshiorder()
    {
        $Timestamp = time();

        $param_to_sign = array(
            "App-Key"      =>    $this->AppKey,
            "Timestamp"    =>    $Timestamp,
            'dsi'=>'e059ca5bedf300dc604231b061982439017ee9nh'
            //"pay_start_time" =>    time()-3600,
            //'pay_end_time'  =>  time()
        );

        $param = array(
            'dsi'=>'e059ca5bedf300dc604231b061982439017ee9nh'
            //"pay_start_time"    => time()-3600,
            //'pay_end_time'      =>  time()
        );

        $sign = $this->get_sign($param_to_sign, $this->accesskey);
        $header = array(
            "App-Key: ".$this->AppKey,
            "Timestamp: ". $Timestamp,
            "Sign: ".$sign
        );
        $ProductList = $this->getProductList();

        //请求生成短链
        $link_response = json_decode($this->get($this->ceshiorderurl, $param, $header), true);
        dump($link_response);die;
        if ($link_response['errno']==0){
            $order_list = $link_response['data'];
            /*foreach ($order_list as $k=>$v){
                $promotion_amount = $v['cps_profit'];
                $commission = $promotion_amount/100*0.56;
                //增加消费记录
                $consume_log_info = UserConsumeLog::get([ 'user_id'=>$v['source_id'], 'order_no'=>$v['order_id']]);
                if (!$consume_log_info){
                    $consume_log_model = new UserConsumeLog();
                    $consume_log_data = [
                        'user_id'=>$v['source_id'],
                        'title'=>$v['title'].$ProductList($v['product_id']),
                        'shop_id'=>0,
                        'shop_name'=>'滴滴',
                        'image'=>'',
                        'order_no'=>$v['order_id'],
                        'pay_time'=>$v['pay_time'],
                        'pay_price'=>$v['pay_price']/100,
                        'consume_type'=>2,
                        'cps_type'=>5,
                        'goods_id'=>$v['product_id'],
                        'commission'=>$commission,
                        'total_commission'=>$promotion_amount,
                        'order_status_name'=>'已付款'
                    ];
                    $consume_log_model->save($consume_log_data);
                    UserConsumeLog::lockMemberConsumeCalculate($v['source_id'],$consume_log_model->total_commission,$consume_log_model->id,0);
                } else {
                    if ($v['order_status']==4){
                        //发放消费记录的收益
                        UserConsumeLog::sendCommission($consume_log_info->order_no);
                    } elseif($v['order_status']==4||$v['order_status']==10) {
                        $consume_log_info->commission = 0;
                        $consume_log_info->order_status_name = '退款成功';
                        $consume_log_info->save();
                    }
                }
            }*/
            return $order_list;
        } else {
            throw new \Exception($link_response['errmsg']);
        }
    }

    public function get_sign($pr, $accesskey)
    {
        ksort($pr);
        $ptr = array();
        foreach ($pr as $key => $val) {
            array_push($ptr, $key . "=" . $val);
        }
        $source = urlencode(implode("&", $ptr)).$accesskey;
        $sign = urlencode(base64_encode(sha1($source)));
        return $sign;
    }


    public function get($url, $params, $header){
        $query = '';
        foreach ($params as $param => $value) {
            $query .= $param.'='.$value .'&';
        }
        $url = $url.'?'.$query;
        $ch = curl_init((string)$url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $parse_url = parse_url($url);
        if($parse_url["scheme"]=="https"){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    public function post($url, $jsonStr, $header){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $parse_url = parse_url($url);
        if($parse_url["scheme"]=="https"){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

}